<template>
  <div>
    <el-dialog :visible="visible"
               v-if="visible1"
               :title="$t('等待支付')"
               @close="handleClose"
               :append-to-body="true"
               width="50%"
               center close-on-click-modal>
      <div style="width:100%;margin-bottom:20px;text-align:center">
        <img v-if="result.payDataType === 'codeImgUrl'" :src="result.payData" alt="">
        <span v-else-if="result.payDataType === 'codeUrl'">{{$t('等待用户支付')}} <hr> {{$t('如浏览器未正确跳转请点击')}}： <a :href="result.payData" target="_blank">支付地址</a><a-button size="small" class="copy-btn" v-clipboard:copy="apiRes.payData" v-clipboard:success="onCopy" >复制链接</a-button></span>
        <span v-else>{{$t('等待用户支付_请稍后')}}</span>
      </div>
      <p class="describe">
        <img src="@/assets/wx_app.svg" alt="" v-show="wxApp"><!-- 微信图标 -->
        <img src="@/assets/ali_app.svg" alt="" v-show="aliApp"><!-- 支付宝图标 -->
        <span>{{ payText }}</span>
      </p>
    </el-dialog>

  </div>
</template>
<script>
import ReconnectingWebSocket from 'reconnectingwebsocket'
import { getWebSocketPrefix } from '@/api/manage'
import {getCurrentUser} from "@/utils";

export default {
  name: 'PayModal',
  props: {
    visible: {},
    result: {}
  },
  model: {
    event: ['closeDialog']
  },
  data () {
    return {
      payText: '', // 二维码底部描述文字
      wxApp: false, // 微信二维码图片是否展示
      aliApp: false, // 支付宝二维码图片是否展示
      apiRes: {}, // 接口返回数据包
      payOrderWebSocket: null, // 支付订单webSocket对象
      visible1: false,
    }
  },
  methods: {
    onBridgeReady() {
      WeixinJSBridge.invoke(
          'getBrandWCPayRequest', JSON.parse(this.apiRes.payData),
          function(res) {
            console.log('响应结果', res)
            if (res.err_msg == "get_brand_wcpay_request:ok") {
              // 使用以上方式判断前端返回,微信团队郑重提示：
              //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
              // //重定向
              window.location.reload()
            }
            if (res.err_msg == "get_brand_wcpay_request:cancel") {
                alert("支付取消");
              // window.WeixinJSBridge.call('closeWindow')
            }
            if (res.err_msg == "get_brand_wcpay_request:fail") {
              alert('支付失败:' + JSON.stringify(res))
              // window.WeixinJSBridge.call('closeWindow')
            }
            if (res.err_msg == "total_fee") {
              alert('服务器异常')
              // window.WeixinJSBridge.call('closeWindow')
            }
          }
      );
    },

    onCopy () {
      this.$message.success(this.$t('复制成功'))
    },

    // 二维码以及条码弹窗
    showModal (wayCode, apiRes) {
      const that = this
      // 关闭上一个webSocket监听
      if (this.payOrderWebSocket) {
        this.payOrderWebSocket.close()
      }

      this.apiRes = apiRes
      this.wxApp = false
      this.aliApp = false
      this.visible1 = true // 打开弹窗
      // console.log(apiRes)
      // console.log(this.visible)
      // 根据不同的支付方式，展示不同的信息
      this.payText = ''
      if (wayCode === 'WX_JSAPI') { // 微信二维码
        this.visible1 = false
        var vm= this;
        if (typeof WeixinJSBridge == "undefined"){//微信浏览器内置对象。参考微信官方文档
          if( document.addEventListener ){
            document.addEventListener('WeixinJSBridgeReady', vm.onBridgeReady(), false);
          }else if (document.attachEvent){
            document.attachEvent('WeixinJSBridgeReady', vm.onBridgeReady());
            document.attachEvent('onWeixinJSBridgeReady',vm.onBridgeReady());
          }
        }else{
          vm.onBridgeReady();
        }
      } else if(wayCode === 'WX_NATIVE'){
        this.wxApp = true
        this.payText = '请使用微信"扫一扫"扫码支付'
      }else if (wayCode === 'ALI_QR' || wayCode === 'ALI_JSAPI') { // 支付宝二维码
        this.aliApp = true
        this.payText = this.$t('请使用支付宝扫一扫扫码支付')
      } else if (wayCode === 'QR_CASHIER') { // 聚合支付二维码
        this.wxApp = true
        this.aliApp = true
        this.payText = this.$t('支持微信_支付宝扫码')
      }

      // 此处判断接口中返回的orderState，值为0，1 代表支付中，直接放行无需处理，2 成功 3 失败
      // if (apiRes.orderState === 2 || apiRes.orderState === 3) {
      //   if (apiRes.orderState === 2) {
      //     that.handleClose()
      //     const succModal = that.$infoBox.modalSuccess('支付成功', <div>2s后自动关闭...</div>)
      //     setTimeout(() => { succModal.destroy() }, 2000)
      //     that.$emit('closeBarCode') // 关闭条码框
      //   } else if (apiRes.orderState === 3) {
      //     that.handleClose()
      //     that.$emit('closeBarCode') // 关闭条码框
      //     that.$infoBox.modalError('支付失败', <div><div>错误码：{ apiRes.errCode}</div>
      //     <div>错误信息：{ apiRes.errMsg}</div></div>)
      //   }
      //   return
      // }

      // h5 或者 wap
      if (wayCode === 'WX_H5' || wayCode === 'ALI_WAP') {
        this.payText = this.$t('请复制链接到手机端打开')
      } else {
      // 跳转到PC网站
        if (apiRes.payDataType === 'payurl') {
          window.open(apiRes.payData)
        }
      }

      // 如果上面未关闭条码框，则代表进入webScoket，那么先在此处关闭条码框
      that.$emit('closeBarCode') // 关闭条码框
      // 监听响应结果
      this.payOrderWebSocket = new ReconnectingWebSocket(getWebSocketPrefix() + '/userapi/api/anon/ws/payOrder/' + apiRes.payOrderId + '/' + new Date().getTime())
      this.payOrderWebSocket.onopen = () => {}
      this.payOrderWebSocket.onmessage = (msgObject) => {
        const resMsgObject = JSON.parse(msgObject.data)
        if (resMsgObject.state === 2) {
          that.handleClose()
          // apiService.get('/currentUserInfo').then(res=>{
          //   if(res.code === 0){
          //     storage.set(appConfig.APP_USER,res.data)
          //   }
          // })
          getCurrentUser('pay')
          const succModal = that.$infoBox.modalSuccess('支付成功', <div>2s后自动关闭...</div>)
          setTimeout(() => { succModal.destroy() }, 2000)
        } else {
          that.handleClose()
          that.$infoBox.modalError('支付失败', <div><div>错误码：{ apiRes.errCode}</div>
          <div>错误信息：{ apiRes.errMsg}</div></div>)
        }
      }
    },
    handleClose () {
      if (this.payOrderWebSocket) {
        this.payOrderWebSocket.close()
      }
      this.$emit('closeDialog', false)
    }
  }
}
</script>
<style lang="less" scoped>
.describe {
  img {
    width: 30px;
    height: 25px;
  }
}
</style>
